package com.dragon.sdgp.common.security;

import cn.hutool.json.JSONUtil;
import com.dragon.sdgp.common.R;
import com.dragon.sdgp.util.JWTUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @AUTHOR : Dragon_Yang
 * @File : LoginSuccessHandler
 * @DESCRIPTION : 登录成功处理器
 * @DATE : 2023/2/27 21:16
 */
//@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username = authentication.getName();
        String token = JWTUtil.Token(username);
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("authorization", token);
        outputStream.write(JSONUtil.toJsonStr(R.success(200, "success", data)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}
